package handler

import (
	"encoding/json"
	"fmt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"go-zero-real/api/demo/internal/logic"
	"go-zero-real/api/demo/internal/svc"
	"go-zero-real/api/demo/internal/types"
	"io"
	"net/http"
)

func DemoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {

	return func(w http.ResponseWriter, r *http.Request) {
		var req types.Request
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewDemoLogic(r.Context(), svcCtx)
		resp, err := l.Demo(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}

}

func respondWithError(w http.ResponseWriter, message string, code int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(map[string]string{"error": message})
}

func TestHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		a, b := getTwoParams()
		fmt.Println(a, b)

		// 从请求中获取文件
		file, header, err := r.FormFile("file") // "file" 是 form-data 中的字段名
		if err != nil {
			respondWithError(w, "Failed to get file: "+err.Error(), http.StatusBadRequest)
			return // 确保在这里返回
		}
		defer file.Close()

		fmt.Printf("Uploaded file: %+v\n", header.Size)

		fileBytes, err := io.ReadAll(file)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return // 确保在这里返回
		}

		fmt.Println("string(fileBytes)", string(fileBytes))

		var req types.TestRequest
		if err := httpx.Parse(r, &req); err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
			return
		}

		l := logic.NewDemoLogic(r.Context(), svcCtx)
		resp, err := l.Test(&req)
		if err != nil {
			httpx.ErrorCtx(r.Context(), w, err)
		} else {
			httpx.OkJsonCtx(r.Context(), w, resp)
		}
	}
}

func getTwoParams() (string, string) {
	return "11", "22"
}
